package com.smartthinking.dive;

import static com.smartthinking.dive.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.smartthinking.dive.CommonUtilities.EXTRA_MESSAGE;
import static com.smartthinking.dive.CommonUtilities.SENDER_ID;
import static com.smartthinking.dive.CommonUtilities.SERVER_URL;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Dictionary;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;

import com.google.android.gcm.GCMRegistrar;

public class Principal extends Activity {

	public Dialog progress;
	Button contacto, acercade;
	AsyncTask<Void, Void, Void> mRegisterTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_principal);
		contacto = (Button) findViewById(R.id.btncontacto);
		
		new AsyncUpdate().execute();
		registerForPush();
	}
	
	public void AcercaDe (View view){
		
		startActivity(new Intent(getApplicationContext(),AcercaDe.class));
		
	}
	
	public void Contacto (View view){
		
		String[] to = { "dive@squenda.com.mx"};
		Intent emailIntent = new Intent(Intent.ACTION_SEND);
		emailIntent.setData(Uri.parse("mailto:"));
		emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
		emailIntent.putExtra(Intent.EXTRA_CC, "");
		emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
		emailIntent.putExtra(Intent.EXTRA_TEXT, "");
		emailIntent.setType("message/rfc822");
		startActivity(Intent.createChooser(emailIntent, "Email "));
		
	}
	public void BotonEvento(View view) {

		startActivity(new Intent(getApplicationContext(),Busqueda_Eventos.class));
	}
	
	public void BotonDirectorio(View view) {

		startActivity(new Intent(getApplicationContext(),Busqueda_Anunciantes.class));
	}
	
	
	
	public class AsyncUpdate extends AsyncTask<Void, Integer, Void>{
		
		ArrayList<Dictionary<String, String> > listaupdate = null;
//		ArrayList<Dictionary<String, String> > Banners = null;
		int isFirstDownload = 0;
		int isNetwork = 0;
		int isOk = 0;
		SharedPreferences preferences;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress = ProgressDialog.show(Principal.this, "",Principal.this.getString(R.string.msg_cargando), true, true, new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					dialog.dismiss();
				}
			});
		}

		@Override
		protected Void doInBackground(Void... params) {
			preferences = Principal.this.getSharedPreferences("prefs", MODE_PRIVATE);
			
			
			//Luego valido la version
			if(preferences.getString("dbversion", "0").equals("0")){
				//primera descarga
				isFirstDownload = 1;
				if(Utilities.isNetwork()){
					isNetwork = 1; 
					String strqry = "select version,fecha from ctrl_updates";
					
					listaupdate = Utilities.qry(Principal.this, strqry.replace(" ", "%20"));
				}else{
					isNetwork = 0;
				}
			}else{
				//actualizacion
				isFirstDownload = 0;
				if(Utilities.isNetwork()){
					isNetwork = 1; 
					String strqry = "select version,fecha from ctrl_updates";
					listaupdate = Utilities.qry(Principal.this, strqry.replace(" ", "%20"));
				}else{
					isNetwork = 0;
				}
			}
			
//		    String qry  = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = 1 and b.ban_nombre = 'BANNER HOME' ORDER BY b.ban_nombre";
//			Banners = Utilities.qry(getApplicationContext(), qry);
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			progress.dismiss();

			if((isFirstDownload == 1)&&(isNetwork == 0)){
				Log.i("1", "(isFirstDownload == 1)&&(isNetwork == 0)");
				AlertDialog.Builder ad = new AlertDialog.Builder(Principal.this);  
				ad.setTitle(Principal.this.getString(R.string.msg_sin_internet));  
				ad.setMessage(Principal.this.getString(R.string.msg_descarga_reintentar));   
				ad.setPositiveButton(Principal.this.getString(R.string.msg_si), new DialogInterface.OnClickListener() {  
					public void onClick(DialogInterface dialog, int id) {  
						dialog.dismiss();
						new AsyncUpdate().execute();
					}  
				}).setNegativeButton(Principal.this.getString(R.string.msg_no), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
//						finish();
					}
				});  
				ad.show();
			}else if((isFirstDownload == 1)&&(isNetwork == 1)){
				Log.i("2", "(isFirstDownload == 1)&&(isNetwork == 1)");
				if(listaupdate.size() > 0){
					AlertDialog.Builder ad = new AlertDialog.Builder(Principal.this);  
					ad.setTitle(Principal.this.getString(R.string.msg_descarga_titulo));  
					ad.setMessage(Principal.this.getString(R.string.msg_descarga));
					ad.setPositiveButton(Principal.this.getString(R.string.msg_si), new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int id) {  
							dialog.dismiss();
							Intent goUpdate = new Intent(Principal.this, UpdateDB.class);
							goUpdate.putExtra("dbversion", ""+listaupdate.get(0).get("version").toString());
							startActivity(goUpdate);
						}  
					}).setNegativeButton(Principal.this.getString(R.string.msg_no), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
//							finish();
						}
					});  
					ad.show();
				}else{
					AlertDialog.Builder ad = new AlertDialog.Builder(Principal.this);  
					ad.setTitle("Error");  
					ad.setMessage("Error del servidor");
					ad.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int id) {  
//							finish();
						}  
					});  
					ad.show();
					
				}
				

			}else if((isFirstDownload == 0)&&(isNetwork == 0)){
				Log.i("3", "(isFirstDownload == 0)&&(isNetwork == 0)");
			}else if((isFirstDownload == 0)&&(isNetwork == 1)){
				Log.i("4", "(isFirstDownload == 0)&&(isNetwork == 1)");
				if(listaupdate.size() > 0){
					if((!preferences.getString("dbversion", "0").equals(""+listaupdate.get(0).get("version").toString()))){
						Log.i("4", "ACTUALIZACION");
						AlertDialog.Builder ad = new AlertDialog.Builder(Principal.this);  
						ad.setTitle(Principal.this.getString(R.string.msg_descarga_titulo));  
						ad.setMessage(Principal.this.getString(R.string.msg_descarga_act));   
						ad.setPositiveButton(Principal.this.getString(R.string.msg_si), new DialogInterface.OnClickListener() {  
							public void onClick(DialogInterface dialog, int id) {  
								dialog.dismiss();
								Intent goUpdate = new Intent(Principal.this, UpdateDB.class);
								goUpdate.putExtra("dbversion", ""+listaupdate.get(0).get("version").toString());
								startActivity(goUpdate);
							}  
						}).setNegativeButton(Principal.this.getString(R.string.msg_no), new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});  
						ad.show();
					}else{
						Log.i("4", "NADA");
					}
				}else{
					AlertDialog.Builder ad = new AlertDialog.Builder(Principal.this);  
					ad.setTitle("Error");  
					ad.setMessage("Error del servidor");
					ad.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int id) {  
//							finish();
						}  
					});  
					ad.show();
				}
				

				
			}//if first download
		}//post-execute
	}
	
	
	private void registerForPush() {
		checkNotNull(SERVER_URL, "SERVER_URL");
		checkNotNull(SENDER_ID, "SENDER_ID");
		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(this);
		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(this);
		//        mDisplay = (TextView) findViewById(R.id.display);
		registerReceiver(mHandleMessageReceiver,
				new IntentFilter(DISPLAY_MESSAGE_ACTION));
		final String regId = GCMRegistrar.getRegistrationId(this);
		Log.i("registerforPUSH", "registerforPUSH *"+regId+"*");
		if (regId.equals("")) {
			// Automatically registers application on startup.
			try {
				Log.i("llevando el registro regID", ""+regId);
				GCMRegistrar.register(this, SENDER_ID);
			} catch (Exception e) {
				e.printStackTrace();
				Log.i("EX", "*"+regId+"*");

			}
			
		} else {
			Log.i("ya registrado regID", ""+regId);

			// Device is already registered on GCM, check server.
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
				//                mDisplay.append(getString(R.string.already_registered) + "\n");

				//            	poner un toast

			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						boolean registered = false;
						try {
							registered = ServerUtilities.register(context, regId);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// At this point all attempts to register with the app
						// server failed, so we need to unregister the device
						// from GCM - the app will try to register again when
						// it is restarted. Note that GCM will send an
						// unregistered callback upon completion, but
						// GCMIntentService.onUnregistered() will ignore it.
						if (!registered) {
//							GCMRegistrar.unregister(context);
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}		
	}

	@Override
	protected void onDestroy() {
		if (mRegisterTask != null) {
			mRegisterTask.cancel(true);
		}
		try {
			unregisterReceiver(mHandleMessageReceiver);
			GCMRegistrar.onDestroy(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		super.onDestroy();
	}

	private void checkNotNull(Object reference, String name) {
		if (reference == null) {
			throw new NullPointerException(
					getString(R.string.error_config, name));
		}
	}

	private final BroadcastReceiver mHandleMessageReceiver =
			new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
			Log.i("Onreceive",newMessage + "\n");
		}
	};

}
